<template>
  <view v-if="show" class="pages">
    <view class="content">
      <view class="title">请选择 <span class="close" @click="show=false">×</span></view>
	  <view class="head">
	    <view >{{ pckrData[0].lablel }}</view>
	    <view >{{ pckrData[1].lablel }}</view>
	    <view >{{ pckrData[2].lablel }}</view>
	  </view>
	  <scroll-view  scroll-y class="indexes" :scroll-into-view="'indexes-'+ listCurID" :style="[{height:'520px'}]" :scroll-with-animation="true" :enable-back-to-top="true">
	    <block v-for="(item,index) in itemArr" :key="index">
	      <view :class="'indexItem-' + index" :id="'indexes-' + index" :data-index="index">
	        <view class="indexItem">{{ indexList[index] }}</view>
	        <view class="cu-list" v-for="(cell, index) in item" @click="checkeData(cell)">
	          <view class="cu-item"  >
	                <text class="">{{ cell .text }}</text>
	          </view>
	        </view>
	      </view>
	    </block>
	  </scroll-view>
	  <view class="indexBar" :style="[{height:'510px'}]">
	    <view class="indexBar-box" @touchstart="tStart" @touchend="tEnd" @touchmove.stop="tMove">
	      <view class="indexBar-item" v-for="(item,index) in indexList" :key="index" :id="index" @touchstart="getCur" @touchend="setCur"> {{ item }}</view>
	    </view>
	  </view>
	  <!--选择显示-->
	  <view v-show="!hidden" class="indexToast">
	    {{ listCur }}
	  </view>
	</view>  
  </view>
</template>

<script lang="ts" setup>
import {reactive,ref,toRefs,watch } from 'vue';
import provinceDataApi from './city-china.json';
import {pinyin} from "./pinyin.js"; 

let level=ref(0); //层级
let pckrData=reactive([
	{value: 0, lablel: '请选择省'},
	{value: 1, lablel: '请选择市'},
	{value: 2, lablel: '请选择区'},
]);
let show=ref(false);
let indexList=reactive([]);
let itemArr=reactive([]);
let provinceData:any=reactive(provinceDataApi); //本地省市区数据
let hidden=ref(true);
let listCurID=ref('');
let listCur=ref('');
let picker:any=reactive([]); //暂存每层数据用于重选

const showCity=()=>{
   console.log(`父组件调用子组件方法showCity`);
   show.value=true;
}

const emit = defineEmits<{
	(event : 'change', pckrData : any) : void,
	(event : 'success', value : string) : void
}>()


//重选
const reelect=()=>{
  level.value=0
  indexList = []
  itemArr = []
  picker=[]
  getDataList()
}

const checkeData=(e:any)=>{
	  indexList = []
	  itemArr = []
	  if (level.value === 0) {
		picker[0] = e
	  }
	  if (level.value === 1) {
		picker[1] = e
	  }
	  if (level.value >= 2) {
		level.value = 2
		picker[2] = e
	  }
	  pckrData[level.value].lablel = e.text
	  pySegSort(e.children)
	  level.value++
	  console.log(level.value)
	  if (level.value === 3) {
		pySegSort(picker[1].children)
		show.value=false
		emit('change',pckrData)
	  }
}

const chineseToInitials=(word:string)=>{
	  let SX = '';
	  for (var i = 0; i < 1; i++) {
		var c = word.charAt(i);
		if (/^[A-Z]+$/.test(c)) {
		  SX += c;
		}
	  }
	  return SX
}
const chineseToPinYin=(l1:string)=>{
	  var l2 = l1.length;
	  var I1 = '';
	  var reg = new RegExp('[a-zA-Z0-9]');
	  for (var i = 0; i < l2; i++) {
		var val = l1.substr(i, 1);
		var name = arraySearch(val, pinyin);
		if (reg.test(val)) {
		  I1 += val;
		} else if (name !== false) {
		  I1 += name;
		}
	  }
	  I1 = I1.replace(/ /g, '-');
	  while (I1.indexOf('--') > 0) {
		I1 = I1.replace('--', '-');
	  }
	  return I1;
}
const arraySearch=(l1:string, l2:string)=>{
      for (var name in pinyin) {
        if (pinyin[name].indexOf(l1) !== -1) {
          return ucfirst(name);
        }
      }
      return false;
}
const ucfirst=(l1:string)=>{
      if (l1.length > 0) {
        var first = l1.substr(0,1).toUpperCase();
        var spare = l1.substr(1,l1.length);
        return first + spare;
      }
}
//列表数据源
const getDataList=()=>{
      indexList = []
      itemArr = []
      pySegSort(provinceData)
}
const pySegSort=(arr:any)=>{
      if (!arr) return
      if (arr.length == 0) return;
      if (!String.prototype.localeCompare) return null;
      var letters = "*ABCDEFGHJKLMNOPQRSTWXYZ".split("");
      var zh = "阿八嚓哒妸发旮哈讥咔垃痳拏噢妑七呥扨它穵夕丫帀".split("");
      var segs:any=reactive([]); // 存放数据
      var res=reactive({});
      let curr:any=reactive({
          initial: '', //字母
          data:[], //数据
        });
      var re = /[^\u4e00-\u9fa5]/; //中文正则
      var pattern = new RegExp(
          "[`\\-~!@#$^&*()=|{}':;',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？12345678990]"); //特殊符号
      letters.filter((items, i) => {
        /* curr = reactive({
          initial: '', //字母
          data: [], //数据
        }); */
        arr.map((v:any, index:number) => {
          // 特殊字符
          if (pattern.test(v.text[0])) {
            if ((!zh[i - 1] || zh[i - 1].localeCompare(v.text) <= 0) && v.text
                .localeCompare(zh[i]) == -1) {
              curr.data.push(v);
            }
          }
          // 判断首个字是否是中文
          // if (uni.$u.test.chinese(v.text[0])) {
            // 英文
            if (chineseToInitials(chineseToPinYin(v.text)) === items) {
              curr.data.push(v);
            }
          // }
        })
        if (curr.data.length) {
          curr.initial = letters[i]
          segs.push(curr);
          curr.data.sort((a, b) => {
            return a.text.localeCompare(b.text);
          });
        }
      })
      segs = Array.from(new Set(segs)) //去重
      segs.forEach((item:any, index:number) => {
        indexList.push(item.initial)
        itemArr.push(item.data)
      })
      // console.log(this.indexList)
      // console.log(this.itemArr)
}

//获取文字信息
const getCur=(e:any)=>{
  hidden.value = false;
  listCur =  indexList[e.target.id];
}

const setCur=(e:any)=>{
  hidden.value = true
  listCur = listCur
}

//滑动选择Item
const tMove=(e:any)=>{
  let y:number = e.touches[0].clientY
  let offsettop:number = 0
  //判断选择区域,只有在选择区才会生效
  if (y > offsettop) {
	let num:number=(y-offsettop)/20;
	listCur = indexList[num];
  }
}
//触发全部开始选择
const tStart=()=>{
  hidden.value = false
}
//触发结束选择
const tEnd=(e:any)=>{
  hidden.value = true;
  listCurID = e.target.id
}
/* watch(
	show,(newval, oldval) => {
		console.log(newval, oldval);
		//props.isShow=newval
    },
    {immediate: true}
); */
/* const props=defineProps({
	isShow:{
		type:Boolean,
		default:false
	},
}) */
defineExpose({
	reelect,
	showCity  //暴露方法
})	
</script>

<style scoped>
.close{
  position: absolute;
  right: 20px;
  font-size: 27px;
  top: 0px;
}
.title{
  padding: 10px 20px  0px 20px;
  text-align: center;
}
.indexItem{
  background: #f8f8f8;
  padding: 10px;
}
.cu-item{
  padding: 10px;
}
.pages>.content{
  /*padding: 10px;*/
  box-shadow: 0 2px 10px 0 #1a1a1a33;
  border-radius: 20px 20px 0 0 ;
}
.pages{
  position: absolute;
  z-index:9999;
  bottom: 3px;
  width: 100%;
  height: 600px;
  background: white;
}
.head{
  font-size: 14px;
  padding: 30rpx;
  display: flex;
  justify-content: space-around;
}
.indexes {
  /*padding: 10px;*/
  position: relative;
}

.indexBar {
  position: fixed;
  right: 0px;
  bottom: 0px;
  padding: 20upx 20upx 20upx 60upx;
  display: flex;
  align-items: center;
}

.indexBar .indexBar-box {
  width: 40upx;
  height: auto;
  background: #fff;
  display: flex;
  flex-direction: column;
  box-shadow: 0 0 20upx rgba(0, 0, 0, 0.1);
  border-radius: 10upx;
}

.indexBar-item {
  flex: 1;
  width: 40upx;
  height: 40upx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24upx;
  color: #888;
}

movable-view.indexBar-item {
  width: 40upx;
  height: 40upx;
  z-index: 9;
  position: relative;
}

movable-view.indexBar-item::before {
  content: "";
  display: block;
  position: absolute;
  left: 0;
  top: 10upx;
  height: 20upx;
  width: 4upx;
  background-color: #f37b1d;
}

.indexToast {
  position: absolute;
  top: 0;
  right: 80upx;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  width: 100upx;
  height: 100upx;
  border-radius: 10upx;
  margin: auto;
  color: #fff;
  line-height: 100upx;
  text-align: center;
  font-size: 48upx;
}
</style>
